package m202311.d14;

/**
 * @author haocongshun
 * @date 2023/11/14 19:38:42
 */

/**
 * 151. 反转字符串中的单词
 */
public class Q151 {

    public String reverseWords(String s) {
        int index = 0;
        StringBuilder sb = new StringBuilder();
        s = s.trim();
        for (int length = s.length() - 1; length >= 0; length--) {
            if (s.charAt(length) != ' ') {
                sb.insert(index, s.charAt(length));
            } else {
                if (sb.charAt(sb.length() - 1) != ' ') {
                    sb.append(" ");
                }
                index = sb.length();
            }
        }
        return sb.toString();
    }

//    public String reverseWords(String s) {
//        String[] split = s.split(" ");
//        StringBuilder rs = new StringBuilder();
//        for (int i = split.length - 1; i >= 0; i--) {
//            if ("".equals(split[i].trim())) {
//                continue;
//            }
//            rs.append(split[i]).append(" ");
//        }
//        return rs.toString().trim();
//    }
}
